package com.htht.smartschool.service.tclass;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.htht.smartschool.common.service.BaseService;
import com.htht.smartschool.model.teacher.TClass;
import com.htht.smartschool.model.teacher.TTeacher;

public class TclassService extends BaseService{

	/***
	 * 按分页获取班级列表
	 * @param currentpage
	 * @param pagesize
	 * @return result
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Map getAllClassByPagesize(TClass tclass) {
		String sql = "SELECT tc.*,tt.name,tt.sex,tt.work,tt.cellphone FROM t_class tc LEFT JOIN t_teacher tt ON tc.teachercode = tt.teachercode where 1 = 1";
		if(!tclass.getType().equalsIgnoreCase("")){
			sql += "  and  tc.type = '"+tclass.getType()+"'";
		}
		if(!tclass.getClasscode().equalsIgnoreCase("")){
			sql += " and tc.classcode = '"+tclass.getClasscode()+"'";
		}
		if( !tclass.getName().equalsIgnoreCase("")){
			sql += " and tt.name like'%"+tclass.getName()+"%'";
		}
		if(!tclass.getSchoolcode().equalsIgnoreCase("")){
			sql += " and tc.schoolcode = '"+tclass.getSchoolcode()+"'";
		}
		 sql += " ORDER BY tc.grade,tc.class asc";
		if(tclass.getRolecode() != null && tclass.getRolecode().length() > 0){
			tclass.setRolecode(tclass.getRolecode().replace(",", "^"));
			sql = "select t1.* from ("+sql+")t1,(select * from t_data_role where rolecode in (:rolecode))t2 where t1.classcode = t2.classcode";
		}
//		String sql2 = "SELECT count(*) FROM t_class tc left join t_teacher tt on tc.teachercode = tt.teachercode";
		List<Object[]> list = getDao().queryBySqlPage(sql, tclass,tclass.getCurrentpage(), tclass.getPagesize());
		 int count = getDao().getCountBySqlPage("select count(*) from ("+sql+") a",tclass);
		List<TClass> result = new ArrayList<TClass>();
		for(int i = 0; i < list.size(); i++){
			TClass tc = new TClass();
			TTeacher tt = new TTeacher();
			Object[] obj = list.get(i);
			tc.setClasscode(String.valueOf(obj[1]));
			tc.setGrade(Integer.parseInt(String.valueOf(obj[2])));
			tc.setClass_(Integer.parseInt(String.valueOf(obj[3])));
			tc.setType(String.valueOf(obj[4]));
			tc.setTeachercode(String.valueOf(obj[5]));
			tt.setName(String.valueOf(obj[7]));
			tt.setSex(String.valueOf(obj[8]));
			tt.setWork(String.valueOf(obj[9]));
			tt.setCellphone(String.valueOf(obj[10]));
			tc.setTeacher(tt);
			result.add(tc);
		}
		Map map = new HashMap();
		map.put("total", count);
		map.put("data", result);
		return map;
	}

	@SuppressWarnings("unchecked")
	public List<TClass> getGradeAndClass(TClass tclass) {
		 
		String sql = "SELECT t.grade, GROUP_CONCAT(t.class ORDER BY t.class ASC) AS classes,GROUP_CONCAT(t.classcode ORDER BY t.class ASC) AS classcodes,t.type FROM t_class t where 1=1";
		if(tclass.getType() != null && tclass.getType().length() > 0){
			sql += " and  t.type = :type";
		}
		if(tclass.getSchoolcode() != null && tclass.getSchoolcode().length() > 0){
			sql += " and t.schoolcode = :schoolcode";
		}
		sql += " GROUP BY t.type,t.grade ORDER BY t.type,t.grade ASC";
		List<Object[]> list = getDao().queryBySQL(sql,tclass);
		List<TClass> result = new ArrayList<TClass>();
		List<TClass> result1 = new ArrayList<TClass>();
		int j = 0;
		for(int i = 0; i < list.size(); i++){
			Object[] obj = list.get(i);
			TClass tc = new TClass();
			TClass tc1 = new TClass();
			if(j == 0){
				tc.setType(String.valueOf(obj[3]));
				tc.setTypeList(result1);
				result.add(tc);
				j++;
			}else{
				if(String.valueOf(obj[3]).equals(result.get(j-1).getType())){
					tc.setTypeList(result1);
				}else{
					result1 = new ArrayList<TClass>();
					tc.setType(String.valueOf(obj[3]));
					tc.setTypeList(result1);
					result.add(tc);
					j++;
				}
			}
			
			tc1.setGrade(Integer.parseInt(String.valueOf(obj[0])));
			tc1.setClasses(String.valueOf(obj[1]));
			tc1.setClasscodes(String.valueOf(obj[2]));
			
			result1.add(tc1);
			
		}
		return result;
	}
	public TClass getClass(TClass tclass) {
		String hql = "From TClass where id IS NOT NULL and schoolcode = :schoolcode";
		hql += " and grade = :grade and class_ = :class_ and type = :type OR classcode = :classcode";
		TClass tc = (TClass) getDao().queryFirstByHQL(hql,tclass);
		return tc;
	}
	public boolean addClass(TClass tclass) {
		TClass tc = getClass(tclass);
		if(tc == null){
			getDao().create(tclass);
			return true;
		}else{
			return false;
		}
	}
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map deleteClasses(String classcode) {
		Map map = new HashMap(); 
		String[] classcodes = classcode.split(",");
		String sql = "delete from t_class where";
		String sql2 = "delete tc,tco from t_course tc,t_courseorder tco where tc.classcode in (";
		String select1 = "";
		String select2 = "";
		for (int i = 0; i < classcodes.length; i++) {
			String ssql = "select grade,class from t_class where classcode = '" + classcodes[i] + "'";
			List li = getDao().queryBySQL(ssql);
			Object[] obj = (Object[]) li.get(0);
			String classname = String.valueOf(obj[0]) + "年级" + String.valueOf(obj[1]) + "班";	
			int count = selectStudentCountByClasscode(classcodes[i]);
			if(count > 0){
				map.put("res"+i, "班级编码" + classname + "存在学生,不能被删除");
			}else{
				select1 += " classcode = '"+classcodes[i]+"' or";
				select2 += "'"+classcodes[i]+"',";
				map.put("res"+i, "班级编码" + classname + "删除成功");
			}
		}
		if(select1 != "" && select2 != ""){
			sql += select1;
			sql2 += select2;
			sql = sql.substring(0,sql.length()-2);
			sql2 = sql2.substring(0,sql2.length()-1);
			sql2 += ") and tco.coursecode = tc.coursecode";
			getDao().executeSQL(sql);
			getDao().executeSQL(sql2);
		}
		return map;
	}
	public int selectStudentCountByClasscode(String classcode){
		String sql = "select count(*) from t_student where classcode = :classcode";
		TClass tclass = new TClass();
		tclass.setClasscode(classcode);
		int count = getDao().getCountBySqlPage(sql,tclass);
		return count;
	}
	public Map updateClass(TClass tclass) {
		Map map = new HashMap();
		TClass tc = getClass(tclass);
		if(tc != null){
			for (Field f : tclass.getClass().getDeclaredFields()) {
			    f.setAccessible(true);
			    try {
					if (f.get(tclass) != null && !f.getName().equalsIgnoreCase("serialVersionUID")) {
					   f.set(tc, f.get(tclass));
					}
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
//			//先去查询 是否含有这个班级
//			String sql  = "select * from t_class where grade = '"+tc.getGrade()+"' and class = '"+tc.getClass_()+"' AND TYPE = '"+tc.getType()+"'";
//			List list = getDao().queryBySQL(sql);
//			if(list.size() > 0){
//				map.put("success", "班级存在");
//			}else{
				//添加
				String usql = " update t_class set classcode='"+tc.getClasscode()+"', grade='"+tc.getGrade()+"', class='"+tc.getClass_()+"', TYPE='"+tc.getType()+"', teachercode='"+tc.getTeachercode()+"', schoolcode='"+tc.getSchoolcode()+"' where id = '"+tc.getId()+"'";
				int a = getDao().executeSQL(usql);
				if(a >= 0){
					map.put("success","修改成功");
				}else{
					map.put("success", "修改失败");
				}
//			}
		}else{
			return map;
		}
		return map;
	}

}
